//index.js
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config')
var util = require('../../utils/util.js')
var payWeChat = require('../../utils/payWeChat.js')
//获取应用实例
var app = getApp()

Page({
  data: {
    goodsList: [],
    isNeedLogistics: 0,
    allGoodsPrice: 0,
    orderType: "",  //  订单类型,默认是购物车
    addrs: [],
    curAddressData: '',
    payment: [
      {name: '微信支付', value: '1', checked: 'true'},
      {name: '货到付款', value: '2'},
    ],
    select:'1',//付款方式：1（微信）2（货到付款）
    out_trade_no:'',
    userid:''
  },

  onLoad: function (e) {
    var that = this
    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
      orderType: e.orderType
    })
  },

  onShow: function () {
    var that = this
    var shopList = []
    //立即购买下单
    if ("buyNow" == that.data.orderType) {
      var buyNowInfoMem = wx.getStorageSync('buyNowInfo')
      if (buyNowInfoMem && buyNowInfoMem.shopList) {
        shopList = buyNowInfoMem.shopList
      }
    } else {
      //购物车下单
      var shopCarInfoMem = wx.getStorageSync('shopCarInfo')
      if (shopCarInfoMem && shopCarInfoMem.shopList) {
        shopList = shopCarInfoMem.shopList.filter(entity => {
          return entity.active
        })
      }
    }
    that.setData({
      goodsList: shopList
    })
    wx.getStorage({
      key:'userInfo',
      success:function(res){
        var userInfoStorage = res.data;
        if (!util.isNUll(userInfoStorage)&&!util.isNUll(userInfoStorage.userid)) {
          app.globalData.userInfo = userInfoStorage;
          that.setData({
            userid:userInfoStorage.userid,
            hasUserInfo: true,
          })
          that.initShippingAddress()
        }else{
          that.login();
        }
      }});
  },
  login: function (callback) {
    var that = this;
    app.login(function(e){
      wx.getStorage({
        key:'userInfo',
        success:function(res){
          let userInfo = res.data;
          app.globalData.userInfo = userInfo;
          that.setData({
            userid:userInfo.userid,
            hasUserInfo: true,
          })
          that.initShippingAddress()
        }
      })})
  },
  // 初始化地址信息
  initShippingAddress: function () {
    var that = this
    wx.request({
      url: config.service.addressList,
      data: {
        userid: that.data.userid
      },
      success: (res) => {
        var addrsList = res.data.data
        for (let i = 0; i < addrsList.length; i++) {
          var temp = addrsList[i]
          if (temp.status == 1) {
            that.setData({
              addrs: addrsList,
              curAddressData: temp
            })
          }
        }
        that.totalPrice()
      }
    })
  },
  // 计算订单总价
  totalPrice: function () {
    var that = this
    var goodsList = this.data.goodsList
    var isNeedLogistics = 0
    var allGoodsPrice = 0
    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i]
      if (carShopBean.logistics) {
        isNeedLogistics = 1
      }
     var discount =1;
      if(carShopBean.has_coupon==0){
        discount = carShopBean.discount;
      }
      var price = parseInt(carShopBean.price/discount);
      allGoodsPrice += (price) * carShopBean.number
    }
    that.setData({
      allGoodsPrice: allGoodsPrice.toFixed(0)
    })
  },
  // 提交订单
  createOrder: function (e) {
    wx.showLoading()
    var that = this
    var remark = ""
    if (e) {
      remark = e.detail.value.remark+'';// 备注信息
    }
      var ordernum = 'M'+this.formatTimeNum(new Date())+Math.floor(9999);
      var zt = 1;
      if (this.data.select==2){
          zt = 2;//确认中
      }

    var postData = {
          userid: this.data.userid,
          total: this.data.allGoodsPrice,
          remark: remark,
          content:'',
          ordernum: ordernum,
          price: this.data.goodsList[0].price,
          amount: this.data.allGoodsPrice,
          name: this.data.curAddressData.name,
          mobile: this.data.curAddressData.tel,
          sheng: this.data.curAddressData.province,
          shi: this.data.curAddressData.city,
          qu: this.data.curAddressData.area,
          address: this.data.curAddressData.address,
          pic:this.data.goodsList[0].pic,
          has_coupon:this.data.goodsList[0].has_coupon,
          discount:this.data.goodsList[0].discount,
          zt: zt,
          zffs:this.data.select,
          insert_time: this.formatTime(new Date())
    }
    if (that.data.isNeedLogistics > 0) {
      if (!that.data.curAddressData) {
        wx.hideLoading()
        wx.showModal({
          title: '错误',
          content: '请先设置您的收货地址！',
          showCancel: false
        })
        return
      }


      var goodslist = this.data.goodsList
        var templist = []
        for (var idx in goodslist) {
            var obj = goodslist[idx]
            var temp = {
                goods_id: obj.goods_id,
                goods_name: obj.name,
                price: obj.price,
                num: obj.number,
                pic: obj.pic,
            }
            templist.push(temp)
        }
        postData.goods = JSON.stringify(templist)

        //postData.address = JSON.stringify({
      //  name: this.data.curAddressData.name,
      //  tel: this.data.curAddressData.tel,
      //  address: this.data.curAddressData.province + this.data.curAddressData.city + this.data.curAddressData.area + this.data.curAddressData.address
      //})
    }
//取消了付款继续付款
    if(that.data.out_trade_no){
      var data = {
        ordernum:that.data.out_trade_no,
        userid: that.data.userid,
        remark: remark,
        name: that.data.curAddressData.name,
        mobile: that.data.curAddressData.tel,
        sheng: that.data.curAddressData.province,
        shi: that.data.curAddressData.city,
        qu: that.data.curAddressData.area,
        address: that.data.curAddressData.address,
        zt: 2,
        zffs:this.data.select,
        content:'',
      };
      wx.request({
            url:config.service.orderFindByOrderNum,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: data,
            success: (res) => {

            if (res.data.code == 0) {
        if (that.data.select==2){
          wx.showToast({
            title: '下单成功,准备发货中',
            icon: 'success',
            duration: 2000
          });
          setTimeout(function () {
            wx.navigateBack();
          }, 2000)
          return;
        }
        var goods = res.data.data;
        payWeChat.payOrder(app.globalData.appid, goods.nonceStr, 'prepay_id=' + goods.prepay_id,goods.amount, goods.ordernum,function(e){
          if(e=='success'){
            wx.showToast({
              title: '下单成功,准备发货中',
              icon: 'success',
              duration: 2000
            });
            setTimeout(function () {
              wx.navigateBack();
            }, 2000)
          }else if(e=='cancel'){
            wx.hideLoading();
          }
        });

      }


    }})
    return;
    }
    wx.request({
      url:config.service.orderAdd,
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      data: postData,
      success: (res) => {
          that.payAction(res);
      }
    })
  },

  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address/index"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/address/index"
    })
  },
  radioChange: function(e) {
    this.data.select = e.detail.value;
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },
     formatTimeNum:function(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    return [year, month, day].join('') + [hour, minute, second].join('')
},
     formatTime:function(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    return [year, month, day].join('-') + ' ' + [hour, minute, second].join(':')
},
  payAction :function(res) {
    var that = this;
    wx.hideLoading()
    if (res.data.code == 0) {
      if (that.data.select==2){
        wx.showToast({
          title: '下单成功',
          icon: 'success',
          duration: 2000
        });
        setTimeout(function () {
          wx.navigateBack();
        }, 2000) //延迟
        return;
      }

      // 微信支付
      var out_trade_no = res.data.data;
      that.setData({
        out_trade_no:out_trade_no
      });
      var total_fee = that.data.allGoodsPrice;
      var goodslist = that.data.goodsList;
      var body = ''
      if (goodslist.length > 1) {
        body = goodslist[0].name + '...等' + goodslist.length + '件商品'
      } else {
        body = goodslist[0].name
      }

      //// 清空购物车已购买商品
      //wx.removeStorageSync('shopCarInfo')
      //写入参数
      var params = new Object();
      params.out_trade_no = out_trade_no;
      params.total_fee = total_fee;
      params.body = body;
      params.pid = goodslist[0].id;
      payWeChat.payWeChat(params,function(e){
        if(e=='success'){
          wx.showToast({
            title: '付款成功,准备发货中',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function(){
            wx.navigateBack({
              delta: 1
            })
          },2000);
        }else if(e=='cancel'){

        }
      });

    } else {
      wx.showModal({
        title: '提示',
        content: res.data.msg,
        showCancel: false,
        success(res) {
        if (res.confirm) {
          wx.navigateBack({})
        }
      }
    })
    }
  },

})
